import { Dialog } from "@/components/dialog";
import type { DataDialogProps } from "@/components/dialog/basic";
import Register from "@/components/dialog/register";
import { useEffect, useState } from "react";
import SchemaForm, { type SchemaFormProps } from "./SchemaForm";
import { Button } from "@/components/ui/button";
import type { FieldValues } from "react-hook-form";
import { toast } from "sonner";

type DataDialogProviderOptions<T extends FieldValues = FieldValues> = Omit<
  DataDialogProps,
  "open" | "onOpenChange" | "children" | "Component" | "componentProps"
> &
  Omit<SchemaFormProps, "onSubmit"> & {
    onSubmit?: (data: T) => Promise<void>;
  };

const channel = new Register<DataDialogProviderOptions>();

// eslint-disable-next-line react-refresh/only-export-components
export const openSchemaForm = channel.open;

const OpenSchemaFormProvider: React.FC<{ id?: string }> = ({ id }) => {
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [options, setOptions] = useState<DataDialogProviderOptions>();

  useEffect(() => {
    channel.register({
      setOptions,
      setOpen,
    });
    return () => {
      channel.unregister(id);
    };
  }, [id]);

  const {
    title,
    description,
    fieldConfigs = [],
    defaultValues,
    onSubmit,
  } = options || {};

  return (
    <Dialog
      open={open}
      onOpenChange={setOpen}
      title={title}
      description={description}
    >
      <SchemaForm
        className="space-y-3"
        fieldConfigs={fieldConfigs}
        defaultValues={defaultValues!}
        onSubmit={async (values) => {
          if (onSubmit) {
            try {
              setLoading(true);
              await onSubmit(values);
            } catch (e) {
              toast.error((e as Error).message || "提交失败");
            } finally {
              setLoading(false);
            }
          }
        }}
      >
        <div className="flex gap-x-2 mt-2 justify-end">
          <Button
            onClick={() => {
              setOpen(false);
            }}
          >
            取消
          </Button>
          <Button type="submit" disabled={loading}>
            确认
          </Button>
        </div>
      </SchemaForm>
    </Dialog>
  );
};

export default OpenSchemaFormProvider;
